using System.Collections;
using UnityEngine;

public class Character : MonoBehaviour
{
    protected Rigidbody2D rb; 
    [Header("生命值")]
    public float maxHealth; // 最大生命值
    protected float _currentHealth; // 当前生命值
    //生命值修改器
    public virtual float CurrentHealth{
        get { return _currentHealth; }
        set{ _currentHealth = value; }
    }

    [Header("无敌")]
    public float invulnerableDuration; // 无敌持续时间
    protected bool invulnerable; // 是否处于无敌状态

    [Header("击退")]
    public Vector2 backPosition;
    [Header("受击特效")]
    public ParticleSystem hitEffects;
    [Header("死亡特效")]
    public ParticleSystem dieEffects;
    [Header("闪白特效")]
    private EntityFX entityFX;
    public bool isDead;
    private void Start()
    {
        CurrentHealth = maxHealth;
        rb = GetComponent<Rigidbody2D>();
        entityFX = GetComponent<EntityFX>();
    }

    // 受到伤害
    public virtual void TakeDamage(Attack attack)
    {
        if(isDead) return;
        if (invulnerable) return; // 如果处于无敌状态，直接返回
        SetHealth(-attack.damage);
        Hit(attack);// 触发受伤逻辑

        if(entityFX) entityFX.PlayFlashFX();

        StartCoroutine(nameof(InvulnerableCoroutine)); // 启动无敌状态的协程
    }

    // 设置生命值
    public virtual void SetHealth(float value)
    {
        CurrentHealth += value;
        if (CurrentHealth >= maxHealth)//超过最大生命值
        {
            CurrentHealth = maxHealth;
        }

        if (CurrentHealth <= 0)// 小于等于0
        {
            CurrentHealth = 0; 
            Die(); // 触发死亡逻辑
        }
    }

    // 受伤逻辑
    protected virtual void Hit(Attack attack)
    {
    }

    // 死亡逻辑
    protected virtual void Die()
    {
    }

    // 无敌状态的协程
    private IEnumerator InvulnerableCoroutine()
    {
        invulnerable = true; // 设置为无敌状态

        yield return new WaitForSeconds(invulnerableDuration); // 等待无敌持续时间

        invulnerable = false; // 结束无敌状态
    }
}
